package com.spooky.sync.note.dialog;

import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.spooky.sync.persistence.dao.CategoryDAO;
import com.spooky.sync.persistence.dao.CategoryDAOBean;
import com.spooky.sync.persistence.entity.Category;

public class CategorySpinner extends Spinner {
	private final Context mContext;

	public CategorySpinner(Context context) {
		super(context);
		mContext = context;
		new CategoryTask().execute();
	}

	public CategorySpinner(Context context, AttributeSet attributeSet) {
		super(context, attributeSet);
		mContext = context;
		new CategoryTask().execute();
	}

	private class CategoryTask extends AsyncTask<String, Integer, List<Category>> {
		private CategoryDAO mCategoryDAO;

		@Override
		protected List<Category> doInBackground(String... params) {
			try {
				return mCategoryDAO.getAll();
			} catch (Exception e) {
			}
			return new LinkedList<Category>();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			mCategoryDAO.close();
		}

		@Override
		protected void onPostExecute(List<Category> result) {
			super.onPostExecute(result);
			if (result.size() == 0) {
				result.add(createDefault());
			}
			mCategoryDAO.close();
			setAdapter(new ArrayAdapter<Category>(mContext, android.R.layout.simple_spinner_dropdown_item, result));
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mCategoryDAO = new CategoryDAOBean(mContext);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		private Category createDefault() {
			Category category = new Category();
			category.setCategory("Default");
			return mCategoryDAO.create(category);
		}
	}
}